package com.yuhanginfo.modules.web.web;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.h2.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.modules.web.util.WebUserUtils;
import com.yuhanginfo.modules.web.entity.PayData;
import com.yuhanginfo.modules.web.entity.WebPayHistory;
import com.yuhanginfo.modules.web.entity.PayResultData;
import com.yuhanginfo.modules.web.entity.WebAddress;
import com.yuhanginfo.modules.web.entity.WebCredit;
import com.yuhanginfo.modules.web.entity.WebInvoiceInfo;
import com.yuhanginfo.modules.web.entity.WebTransactionHistory;
import com.yuhanginfo.modules.web.entity.WebYongUser;
import com.yuhanginfo.modules.web.service.AddressService;
import com.yuhanginfo.modules.web.service.WebPayHistoryService;
import com.yuhanginfo.modules.web.service.WebClassService;
import com.yuhanginfo.modules.web.service.WebCreditService;
import com.yuhanginfo.modules.web.service.WebInvoiceInfoService;
import com.yuhanginfo.modules.web.service.WebTransactionHistoryService;
import com.yuhanginfo.modules.web.util.CodeUtil;
import com.yuhanginfo.modules.web.util.PayUtils;

/**
 * 个人中心->我的信用额度
 *
 */
@Controller
@RequestMapping(value = "${frontPath}/home")
public class HomeController extends BaseController {
	@Autowired
	private WebCreditService webCreditService;
	
	@Autowired
	private WebInvoiceInfoService webInvoiceInfoService;
	
	@Autowired
	private WebTransactionHistoryService webTransactionHistoryService;
	
	@Autowired
	private WebClassService webClassService;
	
	@Autowired
	private WebPayHistoryService payHistoryService;
	
	@Autowired
	private AddressService addressService;

	@RequestMapping(value = "myCredit")
	public String getDefAddress(HttpServletRequest request, HttpServletResponse response, Model model) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		if(yongUser.getId()==null){
			return "modules/web/webLogin";//到登陆页面
		}
		List<WebAddress> addressList = addressService.selectByUserId(Integer.parseInt(yongUser.getId()));
		WebAddress defAddress = null;
		for (WebAddress address : addressList) {
			if("1".equals(address.getIsDef())){
				defAddress = address;
			}
		}
		WebCredit myCredit = webCreditService.selectByUserId(Integer.parseInt(yongUser.getId()));
		model.addAttribute("user", yongUser);
		model.addAttribute("defAddress", defAddress);
		model.addAttribute("actionCenter", "myCredit");
		model.addAttribute("webTransactionHistory", new WebTransactionHistory());
		model.addAttribute("myCredit", myCredit);
		model.addAttribute("allClassesList",webClassService.getAllClasses());
		return "modules/web/home/myCredit";
	}
	
	@RequestMapping(value = "returnMoney")
	public String returnMoney(String isInvoice,WebInvoiceInfo invoiceInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
		WebYongUser yong = WebUserUtils.getYongUser();
		if(yong.getId()==null){
			return "modules/web/webLogin";//到登陆页面
		}
		String returnCode = CodeUtil.getTransactionHistoryReturnCode();
		BigDecimal money = invoiceInfo.getMoney();
		money = money.setScale(2);
		//如果勾选了开票
		if("1".equals(isInvoice)){
			invoiceInfo.setUserId(Integer.parseInt(yong.getId()));
			invoiceInfo.setCode(returnCode);
			invoiceInfo.setStatus(0);
			invoiceInfo.setPayType(2);
			webInvoiceInfoService.save(invoiceInfo);
		}
		WebTransactionHistory history = new WebTransactionHistory();
		history.setUserId(yong.getId());
		history.setType("2");
		history.setCode(returnCode);
		history.setMoney(money);
		history.setDelFlag("1");
		history.setPayType(1);
		webTransactionHistoryService.save(history);
		
		PayData payData = PayUtils.returnMoney(money.toString(), returnCode, invoiceInfo.getId());
		model.addAttribute("payData", payData);
		return "modules/web/payment/sendNew";
	}
	
	@RequestMapping(value = "getMyTransactionHistory")
	@ResponseBody
	public List<WebTransactionHistory> getMyTransactionHistory(String type,String startTime,String endTime) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		WebTransactionHistory webTransactionHistory = new WebTransactionHistory();
		webTransactionHistory.setUserId(yongUser.getId());
		webTransactionHistory.setType(type);
		try {
			if(!StringUtils.isNullOrEmpty(startTime)){
				webTransactionHistory.setStartTime(new SimpleDateFormat("yyyy-MM-dd").parse(startTime));
			}
			if(!StringUtils.isNullOrEmpty(endTime)){
				webTransactionHistory.setEndTime(new SimpleDateFormat("yyyy-MM-dd").parse(endTime));
			}
		} catch (ParseException e) {
			logger.error(e.getMessage(),e);
		}
		return webTransactionHistoryService.selectByUserId(webTransactionHistory);
	}
	
	@RequestMapping(value = "getTransactionType")
	@ResponseBody
	public Map<String,String> getTransactionType(HttpServletRequest request, HttpServletResponse response, Model model) {
		return new HashMap<String, String>();
	}
	
	@RequestMapping(value = "returnMoneySuccess")
	public String returnMoneySuccess(String invoiceInfoId,PayResultData payResultData,HttpServletRequest request, HttpServletResponse response, Model model) {
		WebYongUser yong = WebUserUtils.getYongUser();
		if(yong.getId()==null){
			return "modules/web/webLogin";//到登陆页面
		}
		String returnCode = payResultData.getOrder_id();
		String order_amt = payResultData.getOrder_amt();
		BigDecimal money = new BigDecimal(order_amt);
		money = money.divide(new BigDecimal("100"));
		
		WebCredit credit = webCreditService.selectByUserId(Integer.parseInt(yong.getId()));
		if(credit!=null){
			credit.setRechargeMoney(credit.getRechargeMoney().add(money));
			webCreditService.save(credit);
		}
		
		WebTransactionHistory history = webTransactionHistoryService.selectDelByCode(returnCode);
		if(history!=null){
			history.setDelFlag("0");
			webTransactionHistoryService.save(history);
		}
		WebPayHistory payHistory = new WebPayHistory();
		if(yong.getId()!=null){
			payHistory.setCustomerId(Integer.parseInt(yong.getId()));
		}
		payHistory.setPayResult(2);
		payHistory.setPayCode(payResultData.getOrder_id());
		payHistory.setFySsn(payResultData.getFy_ssn());
		payHistory.setMchntCd(payResultData.getMchnt_cd());
		payHistory.setOrderAmt(money.toString());
		payHistory.setOrderPayCode(payResultData.getOrder_pay_code());
		payHistory.setOrderPayMsg(payResultData.getOrder_pay_error());
		payHistory.setOrderSt(payResultData.getOrder_st());
		payHistory.setOrderDate(payResultData.getOrder_date());
		payHistory.setOrderId(payResultData.getOrder_id());
		payHistory.setPayType(payResultData.getPayType());
		payHistory.setRSA(payResultData.getMd5());
		payHistoryService.save(payHistory);
		model.addAttribute("user", yong);
		model.addAttribute("webTransactionHistory", new WebTransactionHistory());
		model.addAttribute("myCredit", credit);
		model.addAttribute("allClassesList",webClassService.getAllClasses());
		return "redirect:"+ frontPath +"/home/myCredit";
	}
}
